//
//  CuCunTableViewCell.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/5/7.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "CuCunTableViewCell.h"
#import "LineListView.h"
#import "LineView.h"
#import "ShoppingImageScrollView.h"
#import "InterFace.h"
#import "LineView.h"
#import "UIViewAdditions.h"
#import "UIImageView+WebCache.h"
#import "MyListModel.h"

#import "AFNetworking.h"
#import "InterFace.h"
#import "EncryptionData.h"
#import "ProductModel.h"
#import "CategoryModel.h"
#import "JSONKit.h"
#import "ShoppingImageView.h"
#import "CarModel.h"
#import "Alart_ZhiFuView.h"


#import "Reachability.h"
#import "NetStatus.h"
#import "GMDCircleLoader.h"

@implementation CuCunTableViewCell
{
    Alart_ZhiFuView *_zhiFuAlartView;//提交订单时的弹出框
    UIView *_alertBackview;
    
    UITapGestureRecognizer *_singleTap;
    UITapGestureRecognizer *_singleTap2;
}
- (void)awakeFromNib {
    // Initialization code
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView *aview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        [self.contentView addSubview:aview];
        
        //订单号
        self.listNumber = (LineListView *)[[[NSBundle mainBundle] loadNibNamed:@"GeRen_xibs" owner:self options:nil] objectAtIndex:6];
        self.listNumber.frame = CGRectMake(10, aview.bottom, SCREEN_WIDTH-20, 60);
        self.listNumber.address.text = @"";
        self.listNumber.name.hidden = YES;
        self.listNumber.phoneNum.hidden = YES;
        [self.contentView addSubview:self.listNumber];
        
        
        
        //商品滑动图片
        CGRect rect = CGRectMake(0, self.listNumber.bottom-30, SCREEN_WIDTH, (SCREEN_WIDTH-50) / 3.0+40);
//        self.shoppingImageScrollView = [ShoppingImageScrollView  soppingImageScrollViewWithFrame:rect data:array];
        self.shoppingImageScrollView = [[UIScrollView alloc] initWithFrame:rect];
//        self.shoppingImageScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, (SCREEN_WIDTH-50) / 3.0+40);
        [self.contentView addSubview:self.shoppingImageScrollView];
//        
        //线条
        UILabel *lineView2 = [[UILabel alloc] initWithFrame:CGRectMake(10, self.shoppingImageScrollView.bottom+5, SCREEN_WIDTH-20, 1)];
        lineView2.backgroundColor = LineColor;
        [self.contentView addSubview:lineView2];
        
        
        //
        self.lineView = [[[NSBundle mainBundle] loadNibNamed:@"GeRen_xibs" owner:self options:nil] objectAtIndex:7];
        self.lineView.frame = CGRectMake(10, lineView2.bottom+5, SCREEN_WIDTH-20, 40);
        self.lineView.state.text = @"";
        self.lineView.stateLabel.text = @"";
        [self.lineView.queRenBut addTarget:self action:@selector(zhifu) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.lineView];
        
        //线条
        UILabel *lineView3 = [[UILabel alloc] initWithFrame:CGRectMake(0, self.lineView.bottom+5, SCREEN_WIDTH, 10)];
        lineView3.layer.borderWidth = 1.0;
        lineView3.layer.borderColor = BackColor.CGColor;
        lineView3.backgroundColor = LineColor;
        [self.contentView addSubview:lineView3];
        
    }
    return self;
}
//@property (weak, nonatomic) IBOutlet UILabel *listTime; //下单时间
//@property (weak, nonatomic) IBOutlet UILabel *weiShang; //微商关系
//
//@property (weak, nonatomic) IBOutlet UILabel *state;//状态
//
//@property (weak, nonatomic) IBOutlet UIButton *queRenBut;
//
//@property (weak, nonatomic) IBOutlet UILabel *stateLabel;
//
//- (void)createWeiShangArr:(NSArray *)names;


#pragma -mark 给cell上的控件付值
- (void)showCuCunTableViewData:(id)data array:(NSArray *)arr{
            [self.shoppingImageScrollView removeAllSubviews];
    self.shoppingImageScrollView.contentSize = CGSizeMake(SCREEN_WIDTH*(arr.count/3.0), 100);
    for (int i = 0; i < [arr count]; i++) {

        
        ShoppingImageView *shoppingImageView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndex:4];
        
        if ( [[arr[i] class] isSubclassOfClass:[CarModel class]]) {
            CarModel *carModel = arr[i];
            NSURL *url = [NSURL URLWithString:carModel.ThumbPath];
            shoppingImageView.shoppingNumBer.text = [NSString stringWithFormat:@"X%@",carModel.Number];
            shoppingImageView.zeKouJia.text = [NSString stringWithFormat:@"¥%.1f",carModel.MarketAmount.floatValue];
            [shoppingImageView.shoppingImag sd_setImageWithURL:url placeholderImage:nil];
            shoppingImageView.shoppingName.text = carModel.ProductName;
        }
        if ( [[arr[i] class] isSubclassOfClass:[MyListModel class]]) {
            MyListModel *carModel = arr[i];
            NSURL *url = [NSURL URLWithString:carModel.ThumbPath];
            shoppingImageView.shoppingNumBer.text = [NSString stringWithFormat:@"X%@",carModel.BuyAmount];
            shoppingImageView.zeKouJia.text = [NSString stringWithFormat:@"¥%.1f",carModel.DiscountPriceAmount.floatValue];
            [shoppingImageView.shoppingImag sd_setImageWithURL:url placeholderImage:nil];
            shoppingImageView.shoppingName.text = carModel.ProductName;
        }
        
        shoppingImageView.frame = CGRectMake(i * SCREEN_WIDTH / 3.0 + 10 , 10, (SCREEN_WIDTH-50) / 3.0, (SCREEN_WIDTH-50) / 3.0+30);
        
        [self.shoppingImageScrollView addSubview:shoppingImageView];
    }

    MyListModel *listModel = data;
    

    
    
    self.listNumber.listNum.text = [NSString stringWithFormat:@"%@",listModel.MasterOrderID];
    self.listNumber.allPrace.text = [NSString stringWithFormat:@"(¥%.1f)",listModel.TotalAmount.floatValue];
    self.listNumber.zheKouPrace.text = [NSString stringWithFormat:@"¥%.1f",listModel.DiscountAmount.floatValue];
//    self.shoppingImageScrollView
    self.lineView.listTime.text = [NSString stringWithFormat:@"下单时间:%@",listModel.AddTime];

    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"RealName"];
    NSString *FatherAgent = [[NSUserDefaults standardUserDefaults] objectForKey:@"FatherAgent"];
    self.lineView.meLabel.text =userName;
    self.lineView.shangjiLabel.text = FatherAgent;

}
-(void)quZHifu{
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
   
    [GMDCircleLoader setOnView:self withTitle:@"支付中···" animated:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    
    
    
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameter = @{@"AgentID":agentId,@"MasterOrderID":self.listNumber.listNum.text,@"TradePass":_zhiFuAlartView.password.text};
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    
    
    NSString *jsonString = [jsonData base64EncodedStringWithOptions:0];
    
    
    
    NSString *str = [self encodeString:jsonString key:PasswordKey];
    
    NSDictionary *paramer = @{@"sign":str};
    
    __weak CuCunTableViewCell *cuCunCell = self;
    
    [manager POST:ZhiFuInterface parameters:paramer success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [GMDCircleLoader hideFromView:self animated:YES];
        //         sender.userInteractionEnabled = YES;
        NSString *str = responseObject[@"sign"];
        
        
        EncryptionData *data = [[EncryptionData alloc]init];
        NSString *datastr = [data decryption:str :PasswordKey];
        
        NSData* dataFromString = [datastr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSDictionary *dataDic = [NSJSONSerialization  JSONObjectWithData:dataFromString options:NSJSONReadingMutableContainers error:nil];
        
        //返回成功
        if ( [[dataDic objectForKey:@"status"] isEqualToString:@"success"]) {
            
            
            NSLog(@"支付返回结果 ＝＝＝＝ %@",dataDic);
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"支付成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            [cuCunCell.cuCunTableViewCellDelegate getZhiFuEnd];
        } else if ( [[dataDic objectForKey:@"status"] isEqualToString:@"failed"]){
               [cuCunCell.cuCunTableViewCellDelegate zhifuError];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[dataDic objectForKey:@"reason"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        } else{
               [cuCunCell.cuCunTableViewCellDelegate zhifuError];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"服务器错误,支付失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //         sender.userInteractionEnabled = YES;
        [cuCunCell.cuCunTableViewCellDelegate zhifuError];
        NSLog(@"========== %@", [error description]);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
         [GMDCircleLoader hideFromView:self animated:YES];
        
    }];
    

}
#pragma -mark 点击支付
- (void)zhifu{
//    sender.userInteractionEnabled = NO;
    [self careteAlertPassword];
}

-(void)careteAlertPassword{
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate] window];
    
    _alertBackview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _alertBackview.backgroundColor = [UIColor blackColor];
    _alertBackview.alpha = 0.4;
    [windows addSubview:_alertBackview];
    
    _zhiFuAlartView = [[[NSBundle mainBundle] loadNibNamed:@"Shopping_Cart_Xib" owner:self options:nil] objectAtIndexedSubscript:12];
    _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
    _zhiFuAlartView.password.delegate = self;
    [_zhiFuAlartView.affirmBut addTarget:self action:@selector(affirmClick) forControlEvents:UIControlEventTouchUpInside];
    [_zhiFuAlartView.cancelBut addTarget:self action:@selector(cancelButClick) forControlEvents:UIControlEventTouchUpInside];
    [windows addSubview:_zhiFuAlartView];
    
    NSString *title = @"请输入支付密码";
    _zhiFuAlartView.titleAlart.text = title;
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_alertBackview addGestureRecognizer:_singleTap];
    _singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_zhiFuAlartView addGestureRecognizer:_singleTap2];
}
#pragma -mark 点击弹出框的点击手势
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, SCREEN_HEIGHT/2-90, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    [_zhiFuAlartView.password resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if (SCREEN_HEIGHT < 568) {
        
        // beginAnimations表示此后的代码要“参与到”动画中
        
        [UIView beginAnimations:nil context:nil];
        //设置动画时长
        [UIView setAnimationDuration:0.3];
        _zhiFuAlartView.frame = CGRectMake(60, 100, SCREEN_WIDTH-120, 140);
        // commitAnimations,将beginAnimation之后的所有动画提交并生成动画
        [UIView commitAnimations];
    }
    return YES;
}


-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSMutableString *text = [textField.text mutableCopy];
    [text replaceCharactersInRange:range withString:string];
    return [text length] <= 6;
}
#pragma -mark 点击弹出框的确定交易
- (void)affirmClick{
    if (_zhiFuAlartView.password.text== nil ||[_zhiFuAlartView.password.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入支付密码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
    
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [self quZHifu];
}
#pragma -mark 点击弹出框的取消交易
- (void)cancelButClick{
    [_alertBackview removeGestureRecognizer:_singleTap];
    [_zhiFuAlartView removeGestureRecognizer:_singleTap2];
    [_alertBackview removeFromSuperview];
    [_zhiFuAlartView removeFromSuperview];
}

#pragma mark - 加密
-(NSString *)encodeString:(NSString *)data key:(NSString *)key{
    //    NSData* sampleData = [data dataUsingEncoding:NSUTF8StringEncoding];
    //
    //    NSString * base64String = [sampleData base64EncodedStringWithOptions:0];
    NSLog(@"%@",data);
    NSString *result=[[NSMutableString alloc] init];
    NSInteger keyLength = [key length];
    int position = 0;
    int keyChar = 0;
    int strChar = 0;
    for (int i = 0; i < [data length]; i++) {
        position = i % keyLength;
        strChar = [data characterAtIndex:i];
        keyChar =[key characterAtIndex:position];
        int  ch = strChar ^ keyChar;
        char ca = (char) ch;
        result=[result stringByAppendingString:[NSString stringWithFormat:@"%C",ca]];
    }
    
    NSData* sampleDat1a = [result dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString * base64String1 = [sampleDat1a base64EncodedStringWithOptions:0];
    
    return base64String1;
}

@end
